package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.commen.response.JsonResult;
import cn.tedu._05mvcboot02.commen.response.StatusCode;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.AddUserDTO;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "添加用户")
    @PostMapping("insert")
    public JsonResult addUser(AddUserDTO addUserDTO){
        log.debug("addUserDTO = " + addUserDTO);
        User user = new User();
        BeanUtils.copyProperties(addUserDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.OK();
    }
    /**
     * 查询用户列表功能
     */
    @ApiOperation(value = "用户列表")
    @GetMapping("userList")
    public JsonResult selectUserList(){
        List<UserListVO> list = userMapper.selectUserList();
        return JsonResult.ok(list);
    }
    /**
     * 删除指定用户
     */
    @ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "int")
    @ApiOperation(value = "删除用户")
    @GetMapping("delete")
    public JsonResult deleteUser(int id){
        log.debug("id = " + id);
        int i = userMapper.deleteUser(3);
        if(id<0){
            throw new IllegalArgumentException("用户ID值不能小于0");
        }
        if(i>0){
            return JsonResult.OK();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    /**
     * 修改信息
     */
    @ApiOperation(value = "更新用户")
    @PostMapping("update")
    public JsonResult updateUser(User user){
        log.debug("user = " + user);
        userMapper.updateUser(user);
        return JsonResult.OK();
    }

    /**
     * 5.根据用户ID查询指定用户信息
     */
    @ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "int")
    @ApiOperation(value = "查询指定用户")
    @GetMapping(value = "{id}")
    public JsonResult getUserById(@PathVariable(value = "id") int id){
        log.debug("id = " + id);
        User user = userMapper.selectUserById(id);
        return JsonResult.ok(user);
    }
}
